<?php
require_once 'init_app.php';

set_time_limit(0); 

/*$categories = ORM::factory('category')->get_stemmed_categories();
do {
    $products = ORM::factory('product')
                    ->where('is_categorized', '=', 0)
                    ->limit(100)
                    ->find_all();

    foreach ($products as $product) {
        $product->semantic_analyze_category($categories);        
    } 
} while (count($products));*/

$categories = ORM::factory('category')
                        ->where('id', '>', 1775)
                        ->where('id', '<', 2189)
                        ->where('childs', 'IS', NULL)
                        //->where('id', '=', 2075)
                        ->offset(50)
                        ->limit(50)
                        ->find_all()
                        ->as_array();

foreach ($categories as $category) {
    $query = $category->nominative_form.' @product_name '.mb_strtolower($category->name);
    // (толстовки для мальчиков @product_name толстовки)|(водолазки для мальчиков @product_name водолазки)
    if (strstr($category->name, ', ') !== false) {
        $name  = mb_strtolower($category->name);
        $words = explode(', ', $name);
        
        $queries = array();
        foreach ($words as $word) {
            $queries[] = '('.str_replace($name, $word, $category->nominative_form).' @product_name '.$word.')';      
        }
        $query = implode('|', $queries);        
    }
    $query = str_replace('женские', '(женские|женщинам)', $query);
    $query = str_replace('мужские', '(мужские|мужчинам)', $query);
    
    $products = ORM::factory('product')->search($query, null, null, true);
    $n = 0; 
    if (count($products['products'])) {
        $n = DB::update('products')
                ->set(array('category_id' => $category->id, 'is_categorized' => 1))
                ->where('id', 'IN', $products['products'])
                ->where('is_categorized', '=', 0)
                ->execute();     
    } 
    echo $category->id.' - '.$n."\n"; 
}  
 
echo "ok\n";